Package-level declarations
Types
Thrown from AbortSignal.throwIfAborted when the signal has fired.
Member-extensions converting coroutine handles into AbortSignals.
Returned from prepareCall. Any non-null field overrides the agent default for this invocation only.
Provider HTTP/API failure with normalized request and response details.
Approval-identity helpers for PendingApproval.
Provider warning for a call that still completed. Mirrors v6's CallWarning shape without baking provider-specific warning enums into common code.
Content part of a ModelMessage. Sealed so consumers exhaust over variants — adding a new content type forces a compile error at every dispatch site.
The base64 bytes + media type of a downloaded asset.
Downloads a remote asset for PromptConversion.convertToLanguageModelPrompt.
Marks a declaration as experimental: a surface whose shape may change or be removed in any release without going through the normal deprecation cycle.
Why a generation step ended.
GeneratedFile read accessors as member-extensions. Use via member-import (import ai.torad.aisdk.GeneratedFiles.bytes) or with(GeneratedFiles) { ... }.
Final output of Agent.generate. When pendingApprovals is non-empty, the loop paused on tool approval — call Agent.generate again with messages plus tool-approval-response messages to resume.
Prompt material accepted by high-level generators.
Token usage reported by an image model, when available. Mirrors v6's ImageModelUsage.
Marks a declaration as internal to the AI SDK implementation: visible across module boundaries for technical reasons (KMP source sets, inlining), but not part of the supported public contract. It may change or be removed at any time.
JSON-mode instruction injection operations.
Single parameter envelope for both generate and stream so middleware can wrap both the same way and wrapLanguageModel only needs one pass-through shape.
Request metadata recorded by HTTP-backed or gateway providers.
Response metadata recorded by HTTP-backed or gateway providers.
One-shot generate result.
Provider stream plus request/response metadata known before collection.
Tool advertisement at the model surface — the JSON-schema shape the provider needs. Distinct from the application-side Tool which carries a Kotlin executor; this is the wire shape that crosses into a provider.
Loop-termination checks for the tool loop.
Marks direct LanguageModel execution as low-level provider access.
Transport interface for MCP communication. Implementations may wrap stdio, Streamable HTTP, SSE, WebSockets, or a test fixture.
What a middleware receives. Contains:
Which operation a LanguageModelMiddleware.transformParams call is transforming.
Factory helpers for the value-class identifiers. These cannot be expressed as PascalCase faux-constructors because a same-signature fun ProviderId(String) / fun ModelId(String) would conflict with the value-class primary constructors, so they live as members of this object.
v6 wire-shape message — the type passed to LanguageModel generations. Renamed from CoreMessage (v5) per the AI SDK v6 migration.
Drop-everything logger. Default when no DI-injected impl is wired.
Streaming-safe partial-JSON repair + parse operations. Grouped into an object so the helpers stay file-local members rather than loose top-level functions.
Result of PartialJson.parsePartialJson: value is non-null only on the two
Outcome of PartialJson.parsePartialJson, mirroring v6's four state strings.
A pending tool-call approval surfaced from Agent.generate / Agent.stream. Per v6 RPC semantics, generation completes when one or more tools require approval — the host inspects GenerateResult.pendingApprovals, presents UI, and resumes by calling Agent.generate again with messages = result.messages + ToolApprovalResponseMessage(...).
Scope for prepareCall, run once before the loop starts. Useful for RAG context injection, per-user customization, database lookups that shouldn't repeat per step.
Scope for prepareStep, run before every step in the loop. Used for: model routing per step (cheap model for step 1 + 2, expensive for step 3), tool gating per step (only the search tool is callable on step 1), dynamic system prompts, message compression.
Resolves a prompt for a specific model — the port of upstream's convertToLanguageModelPrompt. Grouped as object members because top-level loose functions are disallowed in this codebase; behavior is identical to the prior free-function form.
Typed provider-options boundary (tenet T2).
Wire-level constraint on what shape the model is allowed to emit. Mirrors v6's responseFormat (per call-settings.ts:103-128 → historical parity gap #20). Distinct from Output — Output is the post-decode wrapper that turns text into typed values; ResponseFormat is what the provider sees at call time.
Snapshot of one completed loop step — surfaced to AgentEvent.StepFinished and accumulated in the loop state for PrepareStepScope.steps.
Returned from prepareStep. Any non-null field overrides the agent default / prepareCall value for this step only.
Sealed event stream emitted by LanguageModel.stream and surfaced to application code via Agent.stream. Mirrors the v6 stream-part taxonomy (per packages/ai/src/generate-text/stream-text-result.ts in vercel/ai) adapted to Kotlin sealed classes for exhaustive when.
Streaming generation result — memoised replay. A terminal upstream run is collected at most once; later collectors replay the captured events. If every collector leaves before the upstream reaches a terminal state, that producer is cancelled, its partial buffer is discarded, and a later collector starts a fresh upstream run. To preserve full replay for a collector that attaches after the first event, the result keeps the terminal stream event sequence in memory for the result lifetime. Hosts that need minimum peak memory for a guaranteed single-consumer path can collect the model stream directly instead of using this replaying result surface.
Wires a LanguageModel to the structured-object machinery: constrains the model to emit JSON for schema, streams its text deltas into StructuredObject.phases (the shared parse/validate loop), and surfaces typed partials/value. Mirrors TextGenerator — a PascalCase class, not a camelCase top-level generateObject/streamObject.
Correlation envelope for one agent invocation (one generate/stream call). Every Telemetry event of that invocation carries the same callId, so an integration can reconstruct per-call traces even when a single agent instance serves concurrent calls. agentId/agentVersion mirror Agent.id/Agent.version (parity gap #33: "useful for telemetry"); functionId comes from TelemetrySettings.functionId.
Ordered registry of Telemetry integrations, keyed by Telemetry.name (re-register replaces, keeping the original position).
High-level text generation facade for a single LanguageModel.
Callback invoked when a tool call's JSON arguments fail to decode. Return a corrected ContentPart.ToolCall to retry, or null to give up. Mirrors v6's experimental_repairToolCall.
Whether the LLM should call a tool, no tool, a specific tool, etc.
What Tool.execute receives as its context. Holds the typed application context, abort signal, step number, running message list, and a writer for custom events.
Resource limits for executing tool calls emitted by one agent step.
Abstract base Agent implementation — the canonical v6 ToolLoopAgent. Extend it; do not instantiate it. A concrete agent subclasses this (e.g. class MyAgent(...) : ToolLoopAgent<C, O>(...)) so the agent's identity, tools, lifecycle overrides, and DI live in one named type — never a bare ToolLoopAgent(...) held as a field.
Actions the host dispatches to drive the agent. Mirrors the Action sealed type a Compose ViewModel exposes — the agent is the "model" of an MVI loop.
Options bag passed to predicate callbacks (Tool.needsApproval, Tool.toModelOutput).
Wrapper emitted by Tool.execute — currently only Success; sealed for future variants.
Structured return type for Tool.toModelOutput.
LLM-visible metadata for a Tool. Separates schema from executor.
Bundles selected ToolSchema flags for factory functions.
Lets a tool's executor write custom events into the agent's active output stream. Distinct from the streaming-tool mechanism — pushes arbitrary StreamEvents.
Token-usage tracking, surfaced on completed steps and final results. Per historical parity gap #19, the shape mirrors v6's rich tree — input tokens split into noCache / cacheRead / cacheWrite and output tokens split into text / reasoning plus a raw slot for provider-specific payloads.
Arithmetic over Usage. The + operator lives here as a member-extension (decision-C: no loose top-level funs). Call sites bring it into scope with with(UsageArithmetic) { a + b } or a member import.
Properties
A signal that is never aborted. Useful as a default.
Global registry — upstream v7 registerTelemetry: register once at startup, all calls emit.
Functions
Bind an abort signal to a Job so the signal fires when the job completes (cancelled or otherwise). Lets a parent scope's lifetime automatically cancel anything observing the signal.
Stop only when all conditions report done.
Stop when any of conditions reports done. v6's array-of-conditions shape.
Runtime-typed tool — inputs and outputs are raw JsonElement. Schema is supplied as a JSON string and stored in ToolSchema.metadata under "inputSchema".
Execute a tool outside the agent loop with one-step lookahead semantics.
Creates a Vercel AI Gateway provider.
Stop the moment the named tool is called in any step.
Stock self-healing repair: re-prompt the model with the tool's JSON schema + the failed args + the parse error, asking for corrected JSON. If the second response parses cleanly, return a ContentPart.ToolCall with the corrected input; otherwise return null (the agent loop surfaces StreamEvent.ToolError).
Provider-executed tool: advertises itself to the model but has no local executor.
Stop when the model has emitted the same (toolName, input) tuple n consecutive steps in a row — i.e. the loop is spinning on a tool whose result didn't change the model's behavior. Documented anti-pattern for small / on-device models that can't reason their way out of an unhelpful tool result; surfaced as a hard stop so the host renders the trapped state instead of looping until the step cap.
Creates a cold Flow that emits chunks in order with delayMillis between chunks. The first chunk is emitted immediately; the delay applies only between consecutive chunks.
Stop after n completed steps. v6's default is 20 if stopWhen omitted.
Reified streaming factory — infers serializers from type parameters.
Streaming Tool factory — executor returns Flow
Reified convenience overload — infers serializers from type parameters.
Compose middlewares over model into a new LanguageModel. Order: the first middleware in the list is the outermost wrapper — wrapGenerate runs first on the way in, last on the way out (innermost in the call stack, like Express middleware).